<?php
	class Teaser extends DataObject {
		static $db = array(
			"Title" => "Varchar(255)",
			"Text" => "Text",
			"Template" => "Varchar(255)",
		);
		
		static $has_one = array(
			"LinkTo" => "Page",
		    "TeaserPage" => "TeaserPage"
		);
		
		
		static $field_names = array('Title' => 'Titel'); 
		
		static $template_path = '';
		
		
		function getCMSFields_forPopup() {
	   	
			$fields = new FieldSet();
			
			$templateSource = $this->getTemplateSource();
			
			$fields->push( new TextField( 'Title', 'Titel' ) );
			$fields->push( new SimpleTreeDropdownField('LinkTo','Link') );
			$fields->push( new TextareaField( 'Text','Text' ) );
			$fields->push( new DropdownField( 'Template', 'Template',$templateSource));
			return $fields;
   		}
   		
   		function Link() {
   			$page = DataObject::get_by_id('SiteTree',$this->Page);
   			//var_dump($page);
   			return $page->Link();
   		}
   		
   		function Content() {
   			if ($this->Template) {
   				return $this->renderWith($this->Template);
   			} else
   				return '';
   		}
   		
   		public function getTemplateSource() {
   			$templatePath = $this->getTemplatePath();
   			$templates = array();
   			if(is_dir($templatePath)) {
				$templateDir = opendir( $templatePath );
				// read all files in the directory
				while( ( $templateFile = readdir( $templateDir ) ) !== false ) {
					// *.ss files are templates
					
					if( preg_match( '/(.*)\.ss$/', $templateFile, $match ) ){
						$templates[$match[1]] = $match[1];
					}
				}
			}
			return $templates;
   		}
   		
   		public function getTemplatePath() {
   			//BUG, because _config doesn't get loaded
   			SSViewer::set_theme('mysite');
   			if(file_exists(Director::baseFolder() .'/'.THEMES_DIR."/".SSViewer::current_theme()."/templates/Teaser")){
				return Director::baseFolder() .'/'.THEMES_DIR."/".SSViewer::current_theme()."/templates/Teaser";
   			}
			if(file_exists(Director::baseFolder() .'/teaser/templates/Teaser'))
				return Director::baseFolder() .'/teaser/templates/Teaser';
   		}
		
	}
?>